"use strict";

define({
    encode (x) {
        var x = btoa(unescape(encodeURIComponent(x)));     // UTF-16 -> UTF-8-with-wchar -> base64
        x = x.replace(/[+/]/g, x => ({
            "+": "-",
            "/": "_",
        }[x]));

        var npad = 0;
        while (x.endsWith("=")) {
            npad++;
            x = x.substr(0, x.length-1);
        }
        return x + npad;
    },

    decode (x) {
        var npad = parseInt(x.substr(x.length-1));
        x = x.substr(0, x.length-1) + "=".repeat(npad);

        x = x.replace(/[-_]/g, x => ({
            "-": "+",
            "_": "/",
        }[x]));
        return decodeURIComponent(escape(atob(x)));     // base64 -> UTF-8-with-wchar -> UTF-16
    },
});

